package com.myspringsecurity.filter;

import cn.hutool.json.JSONUtil;
import com.myspringsecurity.entity.Result;
import com.myspringsecurity.utils.JWTUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/11/3 14:50
 * @description：
 * @modified By：
 * @version:
 */
@Component
public class JwtVerifyFilter extends OncePerRequestFilter {
    JWTUtil jwtUtil=new JWTUtil();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        //获取请求路径
        String path = request.getRequestURI();
        //获取请求方式
        String method = request.getMethod();
        if ("POST".equals(method) && "/login".equals(path)){
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头上的token值
        String token = request.getHeader("token");
        //判断是否携带请求token值
        if (StringUtils.hasText(token)){
            //检验token是否有效
            boolean flag = jwtUtil.verify(token);
            if (flag){
                //解析token内容
                Map<String, Object> map = jwtUtil.jieXi(token);
                String username = map.get("username").toString();
                List<String> list=(List<String>)map.get("authorities");
                //把解析的结果封装到securtitContext种，可以交予security判断相应权限
                List<SimpleGrantedAuthority> authorities=list.stream().map(item->new SimpleGrantedAuthority(item)).collect(Collectors.toList());
                UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(username,null,authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request,response);
                return;
            }
        }
        //token为null或者token无效是，相应一个json数据
        PrintWriter writer=response.getWriter();
        Result result=new Result(500,"token无效",null);
        String json = JSONUtil.toJsonStr(result);
        writer.print(json);

        writer.flush();
        writer.close();
    }
}
